<?php


namespace Melon;


use FilesystemIterator;
use SplFileInfo;

class Inotify
{
    protected Application $app;

    protected array $ignoreDir = ['vendor', 'tests'];

    protected string $basePath;

    protected array $fingerprint;

    public function __construct(Application $app)
    {
        $this->app = $app;

        $this->basePath = $this->app->basePath();

        $result = $this->loadFiles($this->basePath);

        $this->fingerprint = $result;
    }

    protected function loadFiles($basePath): array
    {
        $iterator = new FilesystemIterator($basePath);

        $fingerprint = [];

        /** @var SplFileInfo $entry */
        foreach ($iterator as $entry) {
            $relative_path = substr($entry->getRealPath(), strlen($this->basePath) + 1);
            if ($entry->isDir() && !in_array($relative_path, $this->ignoreDir)) {
                $fingerprint = $fingerprint + $this->loadFiles($entry->getRealPath());
            } elseif ($entry->getExtension() == 'php') {
                $fingerprint[$relative_path] = md5_file($entry->getRealPath());
            }
        }

        return $fingerprint;
    }

    public function diff(): bool
    {
        $result = $this->loadFiles($this->basePath);

        return array_diff($result, $this->fingerprint) !== [] || array_diff($this->fingerprint, $result) !== [];
    }
}
